package com.nip.tranning.Activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.nip.trainning.Common.Constant;
import com.nip.trainning.DataTransferObject.PersonDataTable;
import com.nip.trainning.DataTransferObject.PersonEntity;
import com.nip.trainning.SQLiteProject.R;

public class UpdatePeopleActivity extends Activity {
	private Button btnUpdate;
	private Button btnCancel;
	private Intent intentResult;
	private EditText edUName;
	private EditText edUPhone;
	PersonEntity _person;
	private PersonDataTable _personDataTable;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.update_people_activity);
		btnUpdate = (Button) findViewById(R.id.btnUpdate);
		btnCancel = (Button) findViewById(R.id.btnCancel);
		edUName = (EditText) findViewById(R.id.edUName);
		edUPhone = (EditText) findViewById(R.id.edUPhone);
		
		intentResult = getIntent();
		Bundle bundle = intentResult.getExtras();
		
		String path = bundle.getString(Constant.INTENT_CODE_SEND_PATH);
		
		_personDataTable = new PersonDataTable(UpdatePeopleActivity.this, path);
		
		_person = (PersonEntity) bundle
				.getSerializable(Constant.INTENT_CODE_SEND_PEOPLE_UPDATE);

		if (_person == null) {
			return;
		}
		edUName.setText(_person.getPersonName());
		edUPhone.setText(_person.getPhoneNumber());
		
		OnClickListener click = new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int id = v.getId();
				switch (id) {
				case R.id.btnUpdate:
					PersonEntity person = new PersonEntity();
					person.setPersonName(edUName.getText().toString());
					person.setPhoneNumber(edUPhone.getText().toString());
					person.setPersonID(_person.getPersonID());
					
					_personDataTable.UpdatePeople(person);
					
					intentResult.putExtra(Constant.INTENT_CODE_SEND_PEOPLE_UPDATE, true);
					setResult(Constant.INTENT_CODE_RESULT_PEOPLE_UPDATE, intentResult);
					finish();
					break;

				case R.id.btnCancel:
					intentResult.putExtra(Constant.INTENT_CODE_SEND_PEOPLE_UPDATE, false);
					setResult(Constant.INTENT_CODE_RESULT_PEOPLE_UPDATE, intentResult);
					finish();
					break;
				}
			}
		};
		btnUpdate.setOnClickListener(click);
		btnCancel.setOnClickListener(click);
	}
}
